import requests
import argparse

def get_gitee_organization_repos(organization, access_token):
    url = f"https://gitee.com/api/v5/orgs/{organization}/repos"
    headers = {"Authorization": f"token {access_token}"}
    params = {"page": 1, "per_page": 100}
    repos = []

    while True:
        print("Getting repo infomation:", params)
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()
        data = response.json()

        if not data:
            break

        repos.extend(data)
        params["page"] += 1

    return repos

def get_gitee_organization_repo_info(organization, access_token):
    repos = get_gitee_organization_repos(organization, access_token)
    repo_info = {}
    for repo in repos:
        if repo["private"]:
            repo_info[repo["name"]] = "private"
        elif repo["public"]:
            repo_info[repo["name"]] = "public"
        elif repo["internal"]:
            repo_info[repo["name"]] = "internal"
    return repo_info


def write_repo_info(repo_info, file_name, with_visibility):
    print(repo_info)
    with open(file_name, "w") as file:
        for pkgs, visibility in repo_info.items():
            if with_visibility:
                file.write(f"{pkgs}\t{visibility}\n")
            else:
                file.write(f"{pkgs}\n")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Get all repo name in Gitee group.')
    parser.add_argument('token', type=str, help='The access token for the Gitee group, if the user does not have permission, some repos will be invisible.')
    parser.add_argument('--with_visibility', default=True, type=bool, help='Whether the output file with repository visibility, default True.')
    parser.add_argument('--organization', default="opencloudos-stream", type=str, help='The organization name.')
    parser.add_argument('--output_file', default="repo_info_list", type=str, help='The repo name list file.')

    args = parser.parse_args()

    repo_info = get_gitee_organization_repo_info(args.organization, args.token)
    write_repo_info(repo_info, args.output_file, args.with_visibility)

    print(f"已将 {args.organization} 组织内的所有软件包名写入文件：{args.output_file}")
